/*
 * @Author: 小魏
 * @Date: 2019-09-18 17:15:59
 * @LastEditors  : 小魏
 * @LastEditTime : 2020-01-16 17:26:41
 * @Description:
 */
import DisposeImage from "./dispose-image.js"

/**
 * 创建分享画布共用方法：画布参数对象，当前组件this, 配置参数
 * @class CanvasDraw
 * @param  obj, observer, anvasid,
 */
class CanvasDraw extends DisposeImage {
  constructor({
    canvas,
    observer, // 页面this
    options,
  }) {
    super()
    // canvas 上下文对象
    this.ctx = canvas
    // 页面实例 this
    this.observer = observer
    // canvas 配置参数
    this.width = options.width
    this.height = options.height
    this.canvasBgColor = options.bgColor
  }

  // 初始化方法
  init(method) {
    // 绘制画布背景
    this.drawBackground()
    // 调用对应 type 的画布绘制方法
    method()
  }

  /**
  *绘制画布背景（白色）
  * @memberof CanvasDraw
  */
  drawBackground() {
    this.ctx.setFillStyle(this.canvasBgColor);
    this.ctx.fillRect(0, 0, this.width, this.height);
  }

  /**
   * 图片裁剪为原形
   * @param {*} ctx
   * @param {*} img
   * @param {*} x
   * @param {*} y
   * @param {*} r
   * @memberof CanvasDraw
   */
  circleImg(ctx, img, x, y, r) {
    ctx.save();
    var d = 2 * r;
    var cx = x + r;
    var cy = y + r;
    ctx.arc(cx, cy, r, 0, 2 * Math.PI);
    ctx.clip();
    ctx.drawImage(img, x, y, d, d);
    ctx.restore();
  }

  /**
   *保存图片
   *@returns res
   * @memberof CanvasDraw
   */
  drawImage (canvasName) {
    return new Promise((resolve, reject) => {
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: this.width,
        height: this.height,
        destWidth: this.width *5,
        destHeight: this.height *5,
        canvasId: canvasName,
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      }, this.observer)
    })
  }

  /**
   * 画布单位转换
   * @param {*} px
   * @returns
   * @memberof CanvasDraw
   */
  px2rem (px) {
    let windowWidth = wx.getSystemInfoSync().windowWidth
    let rem = windowWidth / 375
    return px * rem
  }
}


export default CanvasDraw